package com.jinhuhang.u2.myselfmodule;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.ColorInt;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jinhuhang.u2.MyApplication;
import com.jinhuhang.u2.R;
import com.jinhuhang.u2.common.api.RetrofitUtils;
import com.jinhuhang.u2.common.constant.Constant;
import com.jinhuhang.u2.entity.AccountBean;
import com.jinhuhang.u2.entity.UserBean;
import com.jinhuhang.u2.invertmodule.CreditorRightsActivity;
import com.jinhuhang.u2.listener.Listener;
import com.jinhuhang.u2.myselfmodule.engine.account.AccountActivity;
import com.jinhuhang.u2.myselfmodule.engine.bank.BankActivity;
import com.jinhuhang.u2.myselfmodule.engine.bid.BidActivity;
import com.jinhuhang.u2.myselfmodule.engine.capital.CapitalActivity;
import com.jinhuhang.u2.myselfmodule.engine.experience.ExperienceActivity;
import com.jinhuhang.u2.myselfmodule.engine.invest.InvestActivity;
import com.jinhuhang.u2.myselfmodule.engine.invite.InviteActivity;
import com.jinhuhang.u2.myselfmodule.engine.message.MessageCenterActivity;
import com.jinhuhang.u2.myselfmodule.engine.recharge.RechargeActivity;
import com.jinhuhang.u2.myselfmodule.engine.setting.SettingActivity;
import com.jinhuhang.u2.myselfmodule.engine.setting.safecenter.PwdActivity;
import com.jinhuhang.u2.myselfmodule.engine.welfare.WelfareActivity;
import com.jinhuhang.u2.myselfmodule.engine.withdraw.WithDrawActivity;
import com.jinhuhang.u2.ui.DefaultDialog;
import com.jinhuhang.u2.ui.Pie;
import com.jinhuhang.u2.ui.PieChart;
import com.jinhuhang.u2.ui.badge.Badge;
import com.jinhuhang.u2.ui.badge.QBadgeView;
import com.jinhuhang.u2.ui.customview.MyDialog;
import com.jinhuhang.u2.ui.itemview.SlideitemView;
import com.jinhuhang.u2.util.RSAEncryptor;
import com.jinhuhang.u2.util.UtilsCollection;
import com.jinhuhang.u2.util.http.HttpWrapper;
import com.jinhuhang.u2.util.http.HttpWrapperList;
import com.jinhuhang.u2.util.http.Result;
import com.jinhuhang.u2.util.http.ResultList;
import com.jinhuhang.u2.util.http.T;
import com.jinhuhang.u2.util.logger.Logger;

import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscription;

/**
 * Created by Jaeger on 16/8/11.
 * <p>
 * Email: chjie.jaeger@gmail.com
 * GitHub: https://github.com/laobie
 */
public class MyAccountFragment extends Fragment {
    @Bind(R.id.account_message)
    ImageView mAccountMessage;
    @Bind(R.id.account_setting)
    ImageView mAccountSetting;
    @Bind(R.id.account_usable)
    TextView mAccountUsable;
    @Bind(R.id.account_collection)
    TextView mAccountCollection;
    @Bind(R.id.account_freeze)
    TextView mAccountFreeze;
    @Bind(R.id.account_headview)
    ImageView mAccountHeadview;
    @Bind(R.id.account_bug_phone)
    TextView mAccountPhone;
    @Bind(R.id.account_recharge)
    TextView mAccountRecharge;
    @Bind(R.id.account_withdraw)
    TextView mAccountWithdraw;
    @Bind(R.id.account_money)
    ImageView mAccountMoney;
    @Bind(R.id.account_capital)
    RelativeLayout mAccountCapital;
    @Bind(R.id.account_invest)
    SlideitemView mAccountInvest;
    @Bind(R.id.account_zqzr)
    SlideitemView mAccountZqzr;
    @Bind(R.id.account_welfare)
    SlideitemView mAccountWelfare;
    @Bind(R.id.account_experience)
    SlideitemView mAccountExperience;
    @Bind(R.id.account_bid)
    SlideitemView mAccountBid;
    @Bind(R.id.account_invite)
    SlideitemView mAccountInvite;
    @Bind(R.id.account_chats)
    PieChart mPieChart;
    @Bind(R.id.account_all)
    LinearLayout mLinearLayout;
    private TextView mTvTitle;
 //   private TextView mTvTitle;
    private View mFakeStatusBar;
    private Activity mActivity;
    private int[] mColors = {R.color.colorPrimary,R.color.red_money,R.color.accountbg};

    private Handler mHandler = new Handler();
    private Badge mBadge;
    private ArrayList mPieList = new ArrayList<>();
    private AccountBean AccountBean;
    private String ZHIFU_PWD = "zhifu";
    public static final String ACCOUNT_DATA = "account_data";
    private UserBean mUser;
    private Subscription mSubscribe;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragement_myaccount, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initBadge();
        mActivity = getActivity();
        initData();
        initListener();
    }

    @Override
    public void onStart() {
        super.onStart();
        /**
         * 请求参数
         */
        mUser = MyApplication.mSpUtil.getUser();
        if(mUser != null) {
            mSubscribe = RetrofitUtils.getInstance().build()
                    .getAccountData(mUser.getUserId())
                    .compose(T.D())
                    .subscribe(new Result<HttpWrapper<AccountBean>>() {
                        @Override
                        protected void onSuccess(HttpWrapper<AccountBean> o) {
                            if (Constant.SUCCESS_CODE == o.code) {
                                showData(o.data);
                            }else {
                                MyApplication.mSpUtil.setAccount(null);
                                MyApplication.mSpUtil.setUser(null);
//                                Intent intent=new Intent(getActivity(), UserActivity.class);
//                                intent.putExtra("type",UserActivity.LOGIN);
//                                startActivity(intent);
                            }
                        }
                    });
        }


        if(mUser != null) {
            mAccountPhone.setText(mUser.getUserName());
            String userId = MyApplication.mSpUtil.getUser().getUserId();

            if (!MyApplication.mSpUtil.getBoolean(ZHIFU_PWD + userId, false)) {
                MyApplication.mSpUtil.putBoolean(ZHIFU_PWD + userId, true);
                DefaultDialog defaultDialog = new DefaultDialog(getActivity());
                defaultDialog.show();
                defaultDialog.setLeft("去修改");
                defaultDialog.setContent("您尚未设置交易密码,当前默认交易密码为登录密码");
                defaultDialog.setRight("暂不修改");
                defaultDialog.setOnNormalAlertDialogChooseClickListener(new Listener.OnNormalAlertDialogChooseClickListener() {
                    @Override
                    public void onLeft() {
                        Intent intent = new Intent(getActivity(), PwdActivity.class);
                        intent.putExtra(PwdActivity.PWD_TYPE, PwdActivity.PWD_TYPE_JIAOYI);
                        startActivity(intent);
                    }

                    @Override
                    public void onRight() {
                        if(mUser.getAssessment()==0 && !MyApplication.mSpUtil.getBoolean("assessment" + userId, false)){
                            MyApplication.mSpUtil.putBoolean("assessment" + userId, true);
                            MyDialog.showAssessment(getActivity());
                        }
                    }
                });
            }else {
                if(mUser.getAssessment()==0 && !MyApplication.mSpUtil.getBoolean("assessment" + userId, false)){
                    MyApplication.mSpUtil.putBoolean("assessment" + userId, true);
                    MyDialog.showAssessment(getActivity());
                }
            }
        }else{
            mAccountPhone.setText("");
        }


    }

    private void initBadge() {
        mBadge = new QBadgeView(getActivity()).bindTarget(mAccountMessage).setBadgeGravity(Gravity.END | Gravity.TOP)
        .setBadgePadding(2,true).setBadgeTextSize(8,true).setGravityOffset(0,0,true).setExactMode(false)
        .setShowShadow(true).setOnDragStateChangedListener((dragState, badge, targetView) -> {
        });
    }

    public void initData() {

    }

    private void showData(AccountBean accountBean) {
        AccountBean = accountBean;
        mPieList.clear();
        MyApplication.mSpUtil.setAccount(AccountBean);
        mAccountUsable.setText(UtilsCollection.connectString("可用余额: ",formatTosepara(Float.parseFloat(accountBean.getUseMoney())),"元"));
        mAccountCollection.setText(UtilsCollection.connectString("累计收益: ",formatTosepara(Float.parseFloat(accountBean.getSumInterest())),"元"));
        mAccountFreeze.setText(UtilsCollection.connectString("冻结金额: ",formatTosepara(Float.parseFloat(accountBean.getNoUseMoney())),"元"));
        mAccountExperience.setTipsOther(accountBean.getVirtualCaptial()+"元");
        mBadge.setBadgeText(accountBean.getUnreadCount());
        String status = null;
        switch (accountBean.getRuleStatus()){
            case "0":
                status = "已开启";
                break;
            case "1":
                status = "未开启";
                break;
            case "2":
                status = "未设置";
                break;
        }

        mAccountBid.setTips(status);

        int useMoney = (int) Double.parseDouble(accountBean.getUseMoney());
        int collectionMoney = (int) Double.parseDouble(accountBean.getSumInterest());
        int noUseMoney = (int) Double.parseDouble(accountBean.getNoUseMoney());
        int all = useMoney + collectionMoney + noUseMoney;
        if(all == 0){
            /**
             * 没有钱
             */
            mPieList.add(new Pie(360F,"60.5", Color.parseColor("#999999")));
            mPieChart.setPie(mPieList);
            mPieChart.startDrawPie();
            return;
        }
        Logger.i((useMoney / (float)all)*360F+"");
        float first = (useMoney / (float) all) * 360F;
        float second = (collectionMoney / (float)all)*360F;
        float three = (noUseMoney / (float)all)*360F;

        float[] arithmetic = UtilsCollection.percentageArithmetic(first,second,three);
        first = arithmetic[0];
        second = arithmetic[1];
        three = arithmetic[2];
        mPieList.clear();

        mPieList.add(new Pie(first,"60.5", Color.parseColor("#0056ad")));
        mPieList.add(new Pie(second,"71.2", Color.parseColor("#DA4453")));
        mPieList.add(new Pie(three,"90.9", Color.parseColor("#dfba00")));
        mPieChart.setPie(mPieList);
        mPieChart.startDrawPie();
    }

    public static String formatTosepara(float data) {
        DecimalFormat df = new DecimalFormat("#,###.00");
        return df.format(data);
    }

    public void initListener() {
        mAccountSetting.setOnClickListener(v -> {
            startActivity(new Intent(mActivity, SettingActivity.class));
        });

        mAccountMessage.setOnClickListener(v -> {
            int count = 0;
            if(AccountBean != null){
                count = Integer.parseInt(AccountBean.getUnreadCount());
            }
            Intent intent = new Intent(mActivity, MessageCenterActivity.class);
            intent.putExtra(MessageCenterActivity.MESSAGE_COUNT,count);
            startActivity(intent);
        });

        mAccountRecharge.setOnClickListener(v -> {
            UserBean user = MyApplication.mSpUtil.getUser();
            String cardNo = RSAEncryptor.androidDecryt(user.getCardNo());
            Logger.e(cardNo+new Gson().toJson(user));
            if(TextUtils.isEmpty(cardNo)){
                /**
                 * 未认证绑卡失败
                 */
                DefaultDialog defaultDialog = new DefaultDialog(getActivity());
                defaultDialog.show();
                goBindBank(defaultDialog);
            }else{
                goRecharge();
            }
        });
        mAccountWithdraw.setOnClickListener(v -> {
            UserBean user = MyApplication.mSpUtil.getUser();
            if("0".equals(user.getStatus())){
                /**
                 * 未认证绑卡失败
                 */
                DefaultDialog defaultDialog = new DefaultDialog(getActivity());
                defaultDialog.show();
                String cardNo = RSAEncryptor.androidDecryt(user.getCardNo());
                if(TextUtils.isEmpty(cardNo)){
                    goBindBank(defaultDialog);
                }else{
                    //去充值
                    defaultDialog.setContent("您尚未完成实名认证,请先进行充值认证");
                    defaultDialog.setLeft("去充值");
                    defaultDialog.setOnNormalAlertDialogChooseClickListener(new Listener.OnNormalAlertDialogChooseClickListener() {
                        @Override
                        public void onLeft() {
                            goRecharge();
                        }

                        @Override
                        public void onRight() {

                        }
                    });
                }
            }else{
                goWithdraw();
            }
        });
        mAccountCapital.setOnClickListener(v -> {
            startActivity(new Intent(mActivity, CapitalActivity.class));
        });
        mAccountInvest.setOnClickListener(v -> {
            startActivity(new Intent(mActivity, InvestActivity.class));
        });
        mAccountZqzr.setOnClickListener(v -> {
            startActivity(new Intent(mActivity, CreditorRightsActivity.class));
        });
        mAccountWelfare.setOnClickListener(v -> {
            startActivity(new Intent(mActivity, WelfareActivity.class));
        });
        mAccountExperience.setOnClickListener(v -> {
            startActivity(new Intent(mActivity, ExperienceActivity.class));
        });
        mAccountBid.setOnClickListener(v -> {
            startActivity(new Intent(mActivity, BidActivity.class));
        });
        mAccountInvite.setOnClickListener(v -> {
            startActivity(new Intent(mActivity, InviteActivity.class));
        });

        mLinearLayout.setOnClickListener(v -> {
            Intent intent = new Intent(mActivity, AccountActivity.class);
            intent.putExtra(ACCOUNT_DATA,MyApplication.mGson.toJson(AccountBean));
            startActivity(intent);
        });
    }

    private void goRecharge(){
        if(AccountBean != null){
            Intent intent = new Intent(mActivity, RechargeActivity.class);
            intent.putExtra("userMoney",AccountBean.getUseMoney());
            startActivity(intent);
        }
    }

    private void goWithdraw(){
        if(AccountBean == null){
            return;
        }
        Intent intent = new Intent(mActivity, WithDrawActivity.class);
        intent.putExtra("withdrawMoney",AccountBean.getWithdrawMoney());
        startActivity(intent);
    }

    private void goBindBank(DefaultDialog defaultDialog){
        //去绑卡
        defaultDialog.setContent("您尚未完成实名认证,请先进行绑定银行卡操作");
        defaultDialog.setLeft("去认证");
        defaultDialog.setOnNormalAlertDialogChooseClickListener(new Listener.OnNormalAlertDialogChooseClickListener() {
            @Override
            public void onLeft() {
                startActivity(new Intent(mActivity, BankActivity.class));
            }

            @Override
            public void onRight() {

            }
        });
    }

    public static boolean setMeizuStatusBarDarkIcon(Activity activity, boolean dark) {
        boolean result = false;
        if (activity != null) {
            try {
                WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                activity.getWindow().setAttributes(lp);
                result = true;
            } catch (Exception e) {
            }
        }
        return result;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mTvTitle = (TextView) view.findViewById(R.id.tv_title);
        mFakeStatusBar = view.findViewById(R.id.fake_status_bar);
    }

    public void setTvTitleBackgroundColor(@ColorInt int color) {
        mTvTitle.setBackgroundColor(color);
        mFakeStatusBar.setBackgroundColor(color);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mSubscribe != null){
            mSubscribe.unsubscribe();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
